package com.situ.servlet;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import com.situ.entity.User;
import com.situ.service.IRoleService;
import com.situ.service.IUserService;
import com.situ.service.impl.RoleServiceImpl;
import com.situ.service.impl.UserServiceImpl;
import com.situ.util.StringUtil;

//用户相关的sevlet
@WebServlet("/user")
@MultipartConfig
public class UserServlet extends HttpServlet {

	private static final long serialVersionUID = 2223554844504036989L;

	IUserService userService = new UserServiceImpl();
	IRoleService roleService = new RoleServiceImpl();
	// 两个参数
	// HttpServletRequest request 请求

	// HttpServletResponse response 响应

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String action = request.getParameter("action");
		switch (action) {
		case "save":
			save(request, response);
			break;
		case "del":
			delete(request, response);
			break;
		case "edit":
			openAddPage(request, response);
			break;
		case "list":
			list(request, response);
			break;
		case "add":
			add(request, response);
			break;
		}
	}

	private void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setAttribute("roles", roleService.selectAllRoles());
		request.getRequestDispatcher("/user/add.jsp").forward(request, response);
	}

	// 查询用户列表数据
	private void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 获取查询条件 username
		String username = request.getParameter("username");
		String name = request.getParameter("name");

		// 每页几条
		Integer pageSize = Integer.parseInt(request.getParameter("pageSize"));
		// 第几页
		Integer pageNum = Integer.parseInt(request.getParameter("pageNum"));

		// 调用userservice 查询出用户数据
		List<User> list = userService.selectUsers(username, name, pageSize, pageNum);

		Integer sum = userService.countUsers(username, name);

		// 把数据放到request里
		request.setAttribute("users", list);
		request.setAttribute("abc", "abc");
		request.setAttribute("pageNum", pageNum);
		request.setAttribute("pageSize", pageSize);
		request.setAttribute("sum", sum);
		// 转发到list.jsp这个页面上
		request.getRequestDispatcher("/user/list.jsp").forward(request, response);

	}

	// 转发用户对象，打开页面
	private void openAddPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String id = request.getParameter("id");
		User user = userService.selectById(id);
		request.setAttribute("user", user);
		request.getRequestDispatcher("/user/add.jsp").forward(request, response);
	}

	// 删除用户数据
	private void delete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String id = request.getParameter("id");
		userService.delUser(id);
		request.getRequestDispatcher("/user/list.jsp").forward(request, response);
	}

	// 保存用户信息
	private void save(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String id = request.getParameter("id");
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String name = request.getParameter("name");
		name = new String(name.getBytes("8859_1"), "utf-8");
		String email = request.getParameter("email");
		String gender = request.getParameter("gender");
		gender = new String(gender.getBytes("8859_1"), "utf-8");
		String birthday = request.getParameter("birthday");
		doUploadFile(request);
		User user = new User();
		user.setUsername(username);
		user.setPassword(password);
		user.setGender(gender);
		user.setEmail(email);
		user.setName(name);
		if (!StringUtil.isEmpty(birthday)) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			try {
				user.setBirthday(sdf.parse(birthday));
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		if (id == null || id.equals("")) {// 没有ID就是新增用户
			userService.addUser(user);
		} else {// 有ID是编辑用户
			user.setId(Integer.parseInt(id));
			userService.updateUser(user);
		}
		request.getRequestDispatcher("/user/list.jsp").forward(request, response);
	}

	private void doUploadFile(HttpServletRequest request) {
		FileOutputStream fos = null;
		InputStream is = null;
		try {
			Part part = request.getPart("avatar");
			if (part.getSize() > 0) {
				fos = new FileOutputStream("/Users/kkkkkk/Desktop/a.png");
				is = part.getInputStream();
				byte[] bs = new byte[1024];
				int len = 0;
				while ((len = is.read(bs)) != -1) {
					fos.write(bs, 0, len);
				}
				fos.flush();
			}
		} catch (Exception e) {

		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doGet(req, resp);
	}

}
